﻿Public Class WP7Button
  Inherits Control

  <CLSCompliant(False)> Public _grayText As Color = Color.FromArgb(110, 110, 110)

  Public Sub New()
  End Sub

  Public Overrides Property Text() As String
    Get
      Return MyBase.Text
    End Get
    Set(ByVal value As String)
      MyBase.Text = value
      Me.Invalidate()
    End Set
  End Property

  Public Property InactiveForeColor() As Color
    Get
      Return Me._grayText
    End Get
    Set(ByVal value As Color)
      Me._grayText = value
      Me.Invalidate()
    End Set
  End Property

  Protected Overrides Sub OnEnabledChanged(ByVal e As System.EventArgs)
    Me.Invalidate()
    MyBase.OnEnabledChanged(e)
  End Sub

  Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
    Static Dim bufWidth As Integer = 0
    Static Dim bufHeight As Integer = 0
    Static Dim buffer As Bitmap = Nothing
    Static Dim bufRect As Rectangle = Rectangle.Empty
    Static Dim pf As New Pen(Me.ForeColor)
    Static Dim pg As New Pen(Me._grayText)
    Static Dim bb As New SolidBrush(Me.BackColor)
    Static Dim bf As New SolidBrush(Me.ForeColor)
    Static Dim gf As New SolidBrush(Me._grayText)

    If Me.Height > 0 AndAlso Me.Width > 0 Then
      If Me.Width <> bufWidth OrElse Me.Height <> bufHeight Then
        ' Setup back buffer and state variables
        bufWidth = Me.Width
        bufHeight = Me.Height

        ' Dispose of the old buffer we don't need anymore.
        If buffer IsNot Nothing Then
          buffer.Dispose()
        End If

        ' Buffer
        buffer = New Bitmap(bufWidth, bufHeight)
        bufRect = New Rectangle(0, 0, bufWidth, bufHeight)
      End If

      ' Create temporary graphics buffer
      Dim g As Graphics = Graphics.FromImage(buffer)

      g.FillRectangle(bb, 0, 0, Me.Width, Me.Height)
      With g.MeasureString(Me.Text, Me.Font)
        If Me.Enabled Then
          g.DrawString(Me.Text, Me.Font, bf, (Me.Width - .Width) >> 1, (Me.Height - .Height) >> 1)
          g.DrawRectangle(pf, 0, 0, Me.Width - 1, Me.Height - 1)
        Else
          g.DrawString(Me.Text, Me.Font, gf, (Me.Width - .Width) >> 1, (Me.Height - .Height) >> 1)
          g.DrawRectangle(pg, 0, 0, Me.Width - 1, Me.Height - 1)
        End If
      End With

      ' Copy back to the front buffer
      g.Dispose()
      e.Graphics.DrawImage(buffer, 0, 0)
    End If
  End Sub

  Protected Overrides Sub OnPaintBackground(ByVal e As System.Windows.Forms.PaintEventArgs)
  End Sub

End Class
